namespace Security.Business.Encrypt
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml.Serialization;
    using System.IO;

    [XmlRoot("Encrypt")]
    public class EncryptConfig
    {
        private static EncryptConfig mCurrent;
        private List<EncryptColumn> mColumns;
        private string mCryptographyType;

        public static EncryptConfig Current
        {
            get
            {
                if (mCurrent == null)
                    mCurrent = EncryptConfig.Load();

                return mCurrent;
            }
        }

        [XmlElement("CryptographyType")]
        public string CryptographyType
        {
            get { return mCryptographyType; }
            set { mCryptographyType = value; }
        }

        [XmlArray("Columns")]
        [XmlArrayItem("Column")]
        public List<EncryptColumn> Columns
        {
            get { return mColumns; }
            set { mColumns = value; }
        }

        public void Save()
        {
            XmlSerializer s = new XmlSerializer(typeof(EncryptConfig));
            TextWriter w = new StreamWriter(GetXmlPath());
            s.Serialize(w, this);
            w.Close();
        }

        public static EncryptConfig Load()
        {
            XmlSerializer s = new XmlSerializer(typeof(EncryptConfig));
            TextReader r = new StreamReader(GetXmlPath());
            EncryptConfig obj = s.Deserialize(r) as EncryptConfig;
            r.Close();
            return obj;
        }

        public ICryptoAlgorithm GetCryptographyObject()
        {
            Type type = Type.GetType(this.CryptographyType);
            return Activator.CreateInstance(type) as ICryptoAlgorithm;
        }

        private static string GetXmlPath()
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Encrypt.xml");
        }
    }

    public class EncryptColumn
    {
        private string mTable;
        private string mName;

        [XmlAttribute("Table")]
        public string Table
        {
            get { return mTable; }
            set { mTable = value; }
        }

        [XmlAttribute("Name")]
        public string Name
        {
            get { return mName; }
            set { mName = value; }
        }
    }
}
